package com.zzy.demo.service.mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class MQTTServiceImpl implements MQTTService{

	@Value("${mqtt.host}")
	private String HOST;
	
	@Value("${mqtt.clientId}")
	private String clientId;
	
	@Autowired
	MqttClient mqttClient;



	/**
	 * 向某个主题发布消息 默认qos：1
	 */
	public void pub(String topic, String msg) {
		MqttMessage mqttMessage = new MqttMessage();
		//mqttMessage.setQos(1);
		mqttMessage.setPayload(msg.getBytes());
		MqttTopic mqttTopic = mqttClient.getTopic(topic);
		
		try {
			MqttDeliveryToken token = mqttTopic.publish(mqttMessage);
			token.waitForCompletion();
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 向某个主题发布消息
	 *
	 * @param topic: 发布的主题
	 * @param msg:   发布的消息
	 * @param qos:   消息质量 Qos：0、1、2
	 */
	public void pub(String topic, String msg, int qos){
		MqttMessage mqttMessage = new MqttMessage();
		mqttMessage.setQos(qos);
		mqttMessage.setPayload(msg.getBytes());
		MqttTopic mqttTopic = mqttClient.getTopic(topic);
		try {
			MqttDeliveryToken token = mqttTopic.publish(mqttMessage);
			token.waitForCompletion();
		} catch (MqttPersistenceException e) {
			e.printStackTrace();
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 订阅某一个主题 ，此方法默认的的Qos等级为：1
	 *
	 * @param topic 主题
	 */
	public void sub(String topic){
		try {
			mqttClient.subscribe(topic);
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 订阅某一个主题，可携带Qos
	 *
	 * @param topic 所要订阅的主题
	 * @param qos   消息质量：0、1、2
	 */
	public void sub(String topic, int qos){
		try {
			mqttClient.subscribe(topic, qos);
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}

	
	
	/**
	 * 关闭MQTT连接
	 */
	public void close(){
		try {
			mqttClient.disconnect();
			mqttClient.close();
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}
	
	

}
